﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.OleDb;
using System.Collections.ObjectModel;
using libConn;
using System.IO;
using CodeReason.Reports;
using System.Windows.Xps.Packaging;
using Microsoft.Win32;

namespace ApartmentSale
{
    public partial class Receipt : Window
    {
        public Receipt()
        {
            InitializeComponent();
        }

        private bool getReceipt()
        {
            string errMessage = null;
            string str = "SELECT * FROM receipt ORDER BY receipt_date";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Get an error receipt information",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false;
            }

            ObservableCollection<ReceiptView> receipts = new ObservableCollection<ReceiptView>();

            try
            {
                foreach (DataRow r in oleDT.Rows)
                {
                    ReceiptView receipt = new ReceiptView(r);
                    receipt.apartment_code = getApartmentCode(receipt.apartment_id);
                    receipts.Add(receipt);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Get an error receipt information", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            dataGrid.DataContext = receipts;
            return true;

        }

        private bool getReceipt(string query, string apartment_code)
        {
            string errMessage = null;
            string str = "SELECT * FROM receipt ";
            str += query;
            str += " ORDER BY  receipt_date";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Get an error receipt information",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false;
            }

            ObservableCollection<ReceiptView> receipts = new ObservableCollection<ReceiptView>();

            try
            {
                foreach (DataRow r in oleDT.Rows)
                {
                    ReceiptView receipt = new ReceiptView(r);

                    receipt.apartment_code = getApartmentCode(receipt.apartment_id);
                    if (apartment_code != "" && receipt.apartment_code.IndexOf(apartment_code) == -1)
                        continue;

                    receipts.Add(receipt);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Get an error receipt information", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            dataGrid.DataContext = receipts;
            return true;
        }

        private string getApartmentCode(int apartment_id)
        {
            if (apartment_id == 0)
            {
                return "";
            }

            string errMessage = null;
            string str = "SELECT apartment_code FROM apartments WHERE apartment_id = " + apartment_id;

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Access to apartment code error",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return "";
            }

            if (oleDT.Rows.Count == 0)
            {
                return "";
            }

            try
            {
                return Convert.ToString(oleDT.Rows[0][0]);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Get an error receipt information", MessageBoxButton.OK, MessageBoxImage.Error);
                return "";
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            getReceipt();
        }

        private void finding()
        {
            string str;
            string apartment_code;

            if (tbCode.Text == "")
            {
                str = "WHERE receipt_code LIKE '%' ";
            }
            else
            {
                str = "WHERE receipt_code LIKE '%" + tbCode.Text + "%' ";
            }

            if (cbStatus.SelectedIndex != -1)
            {
                str += "AND receipt_status = " + cbStatus.SelectedIndex.ToString() + " ";
            }

            if (cbType.SelectedIndex != -1)
            {
                str += "AND receipt_type = " + cbType.SelectedIndex.ToString() + " ";
            }

            if (tbName.Text != "")
            {
                str += "AND receipt_custom_name LIKE '%" + tbName.Text + "%' ";
            }

            if (tbApartmentCode.Text == "")
            {
                apartment_code = "";
            }
            else
            {
                apartment_code = tbApartmentCode.Text;
            }

            DateTime begin, end;
            if (dpBegin.SelectedDate == null)
            {
                begin = DateTime.MinValue;
            }
            else
            {
                begin = (DateTime)dpBegin.SelectedDate;
            }

            if (dpEnd.SelectedDate == null)
            {
                end = DateTime.MaxValue;
            }
            else
            {
                end = ((DateTime)dpEnd.SelectedDate).AddDays(1).AddSeconds(-1);
            }

            str += "AND receipt_date BETWEEN #" + begin.ToString() + "# AND #";
            str += end.ToString() + "#";

            getReceipt(str, apartment_code);
        }

        private void btClear_Click(object sender, RoutedEventArgs e)
        {
            tbCode.Text = "";
            cbStatus.SelectedIndex = -1;
            cbType.SelectedIndex = -1;
            tbName.Text = "";
            tbApartmentCode.Text = "";
            dpBegin.SelectedDate = null;
            dpEnd.SelectedDate = null;

            getReceipt();
        }

        private void btFind_Click(object sender, RoutedEventArgs e)
        {
            finding();
        }

        private DataTable GetDataTable()
        {
            DataTable table = new DataTable("Data Table");

            DataColumn column;
            DataRow row;

            column = new DataColumn();
            column.DataType = Type.GetType("System.Int32");
            column.ColumnName = "receipt_id";
            column.Caption = "ID";
            column.ReadOnly = true;
            column.Unique = true;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "receipt_code";
            column.Caption = "Receipt SN";
            column.ReadOnly = true;
            column.Unique = true;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "receipt_status";
            column.AutoIncrement = false;
            column.Caption = "Status";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);


            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "receipt_type";
            column.AutoIncrement = false;
            column.Caption = "Subject";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.Double");
            column.ColumnName = "receipt_cash_amount";
            column.AutoIncrement = false;
            column.Caption = "Cash";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.Double");
            column.ColumnName = "receipt_card_amount";
            column.AutoIncrement = false;
            column.Caption = "Card";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.Double");
            column.ColumnName = "receipt_check_amount";
            column.AutoIncrement = false;
            column.Caption = "Check";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.Double");
            column.ColumnName = "receipt_amount";
            column.AutoIncrement = false;
            column.Caption = "Amount";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "receipt_custom_name";
            column.AutoIncrement = false;
            column.Caption = "Custom";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "apartment_code";
            column.AutoIncrement = false;
            column.Caption = "Apartment";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "receipt_date";
            column.AutoIncrement = false;
            column.Caption = "Date";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            PrimaryKeyColumns[0] = table.Columns["receipt_id"];
            table.PrimaryKey = PrimaryKeyColumns;

            foreach (ReceiptView receipt in dataGrid.Items)
            {
                row = table.NewRow();
                row["receipt_id"] = receipt.receipt_id;
                row["receipt_code"] = receipt.receipt_code;
                row["receipt_status"] = receipt.status_string;
                row["receipt_type"] = receipt.type_string;
                row["receipt_cash_amount"] = receipt.receipt_cash_amount;
                row["receipt_card_amount"] = receipt.receipt_card_amount;
                row["receipt_check_amount"] = receipt.receipt_check_amount;
                row["receipt_amount"] = receipt.receipt_amount;
                row["receipt_custom_name"] = receipt.receipt_custom_name;
                row["apartment_code"] = receipt.apartment_code;
                row["receipt_date"] = receipt.date_string;
                table.Rows.Add(row);
            }

            DataRow sumRow = table.NewRow();
            sumRow["receipt_id"] = -1;
            sumRow["receipt_code"] = "Sum";

            sumRow["receipt_cash_amount"] = table.Compute("sum(receipt_cash_amount)", "true");
            sumRow["receipt_card_amount"] = table.Compute("sum(receipt_card_amount)", "true");
            sumRow["receipt_check_amount"] = table.Compute("sum(receipt_check_amount)", "true");
            sumRow["receipt_amount"] = table.Compute("sum(receipt_amount)", "true");

            table.Rows.Add(sumRow);

            return table;
        }

        private void btPrint_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.AppStarting;
                ReportDocument reportDocument = new ReportDocument();

                StreamReader reader = new StreamReader(new FileStream(@"Templates\ReceiptReport.xaml", FileMode.Open, FileAccess.Read));
                reportDocument.XamlData = reader.ReadToEnd();
                reportDocument.XamlImagePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Templates\");
                reader.Close();

                ReportData data = new ReportData();

                data.ReportDocumentValues.Add("PrintDate", DateTime.Now);

                DataTable table = GetDataTable();

                data.DataTables.Add(table);

                XpsDocument xps = reportDocument.CreateXpsDocument(data);

                ReportPreview dialog = new ReportPreview();
                dialog.DocView.Document = xps.GetFixedDocumentSequence();

                dialog.Title = "Receipt";

                this.Cursor = Cursors.Arrow;
                dialog.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n\r\n" + ex.GetType() + "\r\n" + ex.StackTrace, ex.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Stop);
            }
        }

        private void btClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
